package com.starbucks.opencase.function;

import com.starbucks.opencase.config.configOC;
import com.starbucks.opencase.data.daCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class funCode {
    @Autowired
    private configOC configOC;
    /**
     * 创建号码
     * @param phone
     * @return
     */
    public String create(String phone){
        Random ran=new Random();
        String code="";
        while(code.length()<6)code+=ran.nextInt(10);
        if(configOC.isTest())daCode.codes.put(phone,"123456");
        else {
            if (!new funDXB().sendCode(phone, code, configOC.getPast_que())) return null;
            daCode.codes.put(phone, code);
        }
        daCode.code_times.put(phone,System.currentTimeMillis());
        System.out.println("phone="+phone+",code="+code);
        return code;
    }

    /**
     * 检测验证码是否超时
     * @param phone
     * @return
     */
    public boolean testPastDue(String phone){
        long t=daCode.code_times.get(phone);
        return System.currentTimeMillis()-t> (configOC.getPast_que()+20)* 1000L;
    }

    /**
     * 删除验证码
     * @param phone
     */
    public void delete(String phone){
        daCode.code_times.remove(phone);
        daCode.codes.remove(phone);
    }

    /**
     * 是否存在验证码
     * @param phone
     * @return
     */
    public boolean exist(String phone){
        return daCode.codes.containsKey(phone);
    }

    /**
     * 检验验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean testCode(String phone,String code){
        if(daCode.codes.containsKey(phone))return daCode.codes.get(phone).equals(code);
        return false;
    }
}
